package cn.fulong.smebj.admin.controller;

import cn.fulong.frame.config.Result;
import cn.fulong.smebj.admin.util.FileUtil;
import cn.fulong.smebj.entity.Maths;
import cn.fulong.smebj.entity.SpecialTopic;
import cn.fulong.smebj.mapper.MathsMapper;
import cn.fulong.smebj.mapper.SpecialTopicMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Api("专题学习")
@RestController
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    private SpecialTopicMapper specialTopicMapper;

    @Value("${application.upload-path}")
    private String uploadPath;

    @ApiOperation("管理列表")
    @RequestMapping(value = "/list")
    public Result<Object> list(Integer pageNo, Integer pageSize) {
        IPage<Map<String,Object>> iPage = new Page<>(Optional.ofNullable(pageNo).orElse(0), pageSize);
        IPage<SpecialTopic> result = specialTopicMapper.queryList(iPage);
        return Result.success(result);
    }


    @ApiOperation("保存专题")
    @PostMapping(value = "/save")
    public Result<Object> save(String title,@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extPath = "topic/"+ title+ "/"+originalFilename;
        String path = uploadPath+extPath;
        StringBuilder fileUrl = new StringBuilder("/");
        try {
            File folderFile = new File(path);
            if(!folderFile.exists()){
                String[] splitFolder = path.split("/");
                //递归创建文件夹
                for (int i = 0; i < splitFolder.length; i++) {
                    String url = splitFolder[i];
                    if(StringUtils.isEmpty(url)){
                        continue;
                    }
                    fileUrl.append(url).append("/");
                    File childUrl = new File(String.valueOf(fileUrl));
                    if(!childUrl.exists()){
                        childUrl.mkdir();
                    }
                }
            }
            file.transferTo(new File(path).getCanonicalFile());
            SpecialTopic topic = new SpecialTopic();
            topic.setFileName(originalFilename);
            topic.setFilePath(extPath);
            topic.setTitle(title);
            topic.setCreateTime(new Date(System.currentTimeMillis()));
            specialTopicMapper.insert(topic);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @ApiOperation("更新专题")
    @PostMapping(value = "/update")
    public Result<Object> update(Long id,String title,@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extPath = "topic/"+ title+ "/"+originalFilename;
        String path = uploadPath+extPath;
        StringBuilder fileUrl = new StringBuilder("/");
        try {
            File folderFile = new File(path);
            if(!folderFile.exists()){
                String[] splitFolder = path.split("/");
                //递归创建文件夹
                for (int i = 0; i < splitFolder.length; i++) {
                    String url = splitFolder[i];
                    if(StringUtils.isEmpty(url)){
                        continue;
                    }
                    fileUrl.append(url).append("/");
                    File childUrl = new File(String.valueOf(fileUrl));
                    if(!childUrl.exists()){
                        childUrl.mkdir();
                    }
                }
            }
            SpecialTopic topic = specialTopicMapper.selectById(id);
            if(file==null){
                file.transferTo(new File(path).getCanonicalFile());
                topic.setFileName(originalFilename);
                topic.setFilePath(extPath);
            }
            topic.setTitle(title);
            topic.setCreateTime(new Date(System.currentTimeMillis()));
            specialTopicMapper.updateById(topic);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @ApiOperation("删除专题")
    @PostMapping(value = "/delete")
    public Result<Object> delete(Long id) {
        SpecialTopic topic = specialTopicMapper.selectById(id);
        String path = topic.getFilePath();
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
        specialTopicMapper.deleteById(id);
        return Result.success();
    }

    @ApiOperation("下载附件")
    @PostMapping(value = "/download")
    public Result<Object> downLoadZipFile(HttpServletResponse response, Long id) {
        SpecialTopic topic = specialTopicMapper.selectById(id);
        String path = topic.getFilePath();
        File file = new File(path);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success();
    }
}
